<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaWebsocketDemo</title>
    <script type="text/javascript" src="../static/jquery-3.6.0.min.js" th:src="@{/jquery-3.6.0.min.js}"></script>
    <script>
        let websocket = null
        function connectWebsocket() {
            let nickname = $("#nickname").val()
            if (nickname == null || nickname === "") {
                alert("昵称不为空!")
                return
            }
            if ("WebSocket" in window) {
                websocket = new WebSocket("ws://localhost:8080/websocket/" + nickname);
            } else {
                alert("此浏览器不支持websocket!")
                return
            }
            websocket.onerror = function () {
                setMessageInnerHTML("error")
            }
            websocket.onopen = function (event) {
                console.log(event)
                setMessageInnerHTML("连接成功")
            }
            websocket.onmessage = function (event) {
                console.log(event)
                setMessageInnerHTML(event.data)
            }
            websocket.onclose = function (event) {
                console.log(event)
                setMessageInnerHTML("连接关闭")
            }
            //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
            window.onbeforeunload = function () {
                websocket.close()
            }
        }

        function closeWebsocket() {
            if (websocket != null) {
                websocket.close()
            }
        }

        function sendMsg() {
            let message = $("#text").val()
            let toUser = $("#toUser").val()
            let msgData = {message: message, toUser: toUser}
            msgData.type = toUser === "" ? 0 : 1
            if (websocket != null) {
                websocket.send(JSON.stringify(msgData))
            } else {
                alert("未连接")
            }
        }

        function setMessageInnerHTML(message) {
            $("#message").append("<p>" + message + "</p>")
        }
    </script>
</head>
<body>
<header>
    <meta http-equiv="Content-Type" charset="utf-8">
</header>
<div>
    <label for="nickname">昵称: </label><input type="text" id="nickname"/>
    <button onclick="connectWebsocket()">连接WebStock</button>
    <button onclick="closeWebsocket()">断开连接</button>
    <hr/>
    <br/>
    <label for="text">消息: </label><input id="text" type="text"/>
    <label for="toUser">接收者: </label><input id="toUser" type="text"/>
    <button onclick="sendMsg()">发送消息</button>
    <div id="message"></div>
</div>
</body>
</html>